import { Toast } from 'antd-mobile';
const defaultState = {
  arr: [],
  title: '1710A-项目实战',
  initData: [],
  cartData: [],
  totalCheck: false, // 全选
}

export default (state = defaultState, action) => {
  // 拷贝数据  修改数据  返回确定数据
  const newState = JSON.parse(JSON.stringify(state));

  // 全选按钮
  if (action.type === 'change_total_check') {
    newState.totalCheck = action.flag;
    // 实现全选反选功能
    newState.cartData.forEach((item) => {
      item.itemCheck = action.flag
    })
  }

  // 单选按钮
  if (action.type === 'change_item_check') {
    // 循环数据实现 点击每一个input的选中效果
    newState.cartData.forEach((item) => {
      if (item.id === action.opt.id) {
        item.itemCheck = action.opt.flag
      }
    })
    // 全选
    newState.totalCheck = newState.cartData.every((item) => {
      return item.itemCheck
    })
  }

  if (action.type === 'init_cart_data') {
    newState.initData = action.data;
  }

  if (action.type === 'to_cart') {
    let goods = newState.cartData.find(v => v.id === action.item.id)
    if (goods) {
      goods.count++
    } else {
      action.item.count = 1;
      newState.cartData.push(action.item)
    }
    Toast.success('已经加入购物车', 1);
  }

  if (action.type === 'add_cart_item') {
    newState.cartData[action.index].count++;
  }

  if (action.type === 'remove_cart_item') {
    newState.cartData[action.index].count--;
  }

  if (action.type === 'delete_item') {
    newState.cartData.splice(action.index, 1)
  }

  return newState;
}